import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/finished_out_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_move_line_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_quant_odoo_api.dart';
import 'package:flutter_admin/models/odoo/stock_quant.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/finish_out.dart';
import 'package:flutter_admin/pages/odoo/material/finished_out/delivery.dart';
import 'package:flutter_admin/pages/odoo/material/finished_out/ship_the_products.dart';
import 'package:flutter_admin/pages/odoo/material/hw_quant_search/hw_quant_search_detail_list.dart';
import 'package:flutter_admin/pages/odoo/material/location_out/location_out_confirmation.dart';
import 'package:flutter_admin/pages/odoo/material/stock_quant/stock_quant_search_dialog.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class HWQuantSearchList extends StatefulWidget {
  HWQuantSearchList({Key? key}) : super(key: key);

  @override
  _HWQuantSearchListState createState() => _HWQuantSearchListState();
}

class _HWQuantSearchListState extends State<HWQuantSearchList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
  PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  List<StockQuant> selectedList = [];
  //车间
  List<SelectOptionVO> workshopList = [];
  //库房
  List<SelectOptionVO> locationList = [];

  StockQuant stockQuant = StockQuant();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    locationList = await DynamicDataApi.getModelSelect(
        active: false,
        model: "stock.location",
        name: "complete_name",
        key: 'father_locaiton',
        val: null
    );
    setState(() {});
  }


  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          // CrySelect(
          //   width: 240,
          //   label: '生产车间',
          //   dataList: workshopList,
          //   value: stockQuant.workshopId,
          //   onSaved: (v) {
          //     stockQuant.workshopId = v;
          //   },
          //   onChange: (v) async {
          //     if (stockQuant.workshopId != v) {
          //       formKey.currentState!.save();
          //       stockQuant.workshopId = v;
          //       stockQuant.locationId = null;
          //       try {
          //         locationList = await DynamicDataApi.getModelSelect(
          //             active: false,
          //             model: "stock.location",
          //             name: "complete_name",
          //             key: 'workshop_id',
          //             val: int.parse(v),
          //             key2: 'father_locaiton',
          //             val2: null
          //         );
          //       } catch (e) {
          //         locationList = [];
          //       }
          //       setState(() {});
          //     }
          //   },),
          CrySelect(
            width: 380,
            label: '库房',
            dataList: locationList,
            value: stockQuant.locationId,
            onSaved: (v) {
              stockQuant.locationId = v;
            },
          ),
          CryInput(
            width: 160,
            label: '物料编码',
            value: stockQuant.productCode,
            onSaved: (v) {
              stockQuant.productCode = v;
            },
          ),
          CryInput(
            width: 160,
            label: '销售单号',
            value: stockQuant.saleorder,
            onSaved: (v) {
              stockQuant.saleorder = v;
            },
          ),
          CryInput(
            width: 160,
            label: '生产单号',
            value: stockQuant.productorderno,
            onSaved: (v) {
              stockQuant.productorderno = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
        _operationList(),
      ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('销售单号')),
        DataColumn(label: Text('生产单号')),
        DataColumn(label: Text('库房位置')),
        DataColumn(label: Text('物料编码')),
        DataColumn(label: Text('物料名称')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('库存数量')),
        DataColumn(label: Text('单位')),
      ],
      getCells: (m) {
        // StockQuant stockQuant = StockQuant.fromHWSearchMap(m);
        StockQuant stockQuant = StockQuant.fromHWMap(m);

        return [
          DataCell(Text(stockQuant.saleorder ?? '--')),
          DataCell(Text(stockQuant.productorderno ?? '--')),
          DataCell(Text(stockQuant.locationName ?? '--')),
          DataCell(Text(stockQuant.productCode ?? '--')),
          DataCell(Text(stockQuant.productName ?? '--')),
          DataCell(Text(stockQuant.productDes ?? '--')),
          DataCell(Text(stockQuant.quantity.toString())),
          DataCell(Text(stockQuant.productUomName ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButton(
            label: '查看明细',
            iconData: Icons.view_agenda_rounded,
            onPressed: selectedList.length == 1
                ? () => _openDetail(selectedList[0])
                : null),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _openDetail(StockQuant stockQuant) {
    Utils.fullscreenDialog(HWQuantSearchDetailList(
      huaweiCheckId: stockQuant.id!,
    ));
  }

  _reset() {
    stockQuant = StockQuant();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await StockQuantOdooApi.HWPage(
        data: {"page": page, "domainList": stockQuant.toHWSearchDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
    // ResponseBodyApi responseBodyApi = await StockQuantOdooApi.HWSearchPage(
    //     data: {"page": page, "domainList": stockQuant.toHWSearchDomainList()});
    // if (responseBodyApi.success!) {
    //   page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
    //   tableKey.currentState!.loadData(page);
    //   _getSelectList();
    // }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: StockQuantSearchDialog(),
      ),
    ).then((v) {
      if (v != null) {
        stockQuant = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
        ?.getSelectedList(page)
        .map<StockQuant>((e) => StockQuant.fromHWMap(e))
        .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _openDetail(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled: selectedList.length == 1,
            title: Text('查看明细'),
          ),
        ),
      ],
    );
  }
}
